package com.ctp.api.util;

import java.util.concurrent.TimeUnit;

import org.hraink.futures.ctp.thostftdcuserapidatatype.ThostFtdcUserApiDataTypeLibrary.THOST_TE_RESUME_TYPE;
import org.hraink.futures.ctp.thostftdcuserapistruct.CThostFtdcQryTradingAccountField;
import org.hraink.futures.jctp.md.JCTPMdApi;
import org.hraink.futures.jctp.md.JCTPMdSpi;
import org.hraink.futures.jctp.trader.JCTPTraderApi;
import org.hraink.futures.jctp.trader.JCTPTraderSpi;

import com.ctp.api.base.MyMdSpi;
import com.ctp.api.base.MyTraderSpi;
import com.ctp.bean.constants.ServerParams;
import com.ctp.display.thread.HeartBeatThread;

public class TraderUtil {

	private static TraderUtil instance = new TraderUtil();

	private JCTPMdApi mdApi = null;
	private JCTPTraderApi tdApi = null;

	private JCTPMdSpi mdSpi = null;
	private JCTPTraderSpi tdSpi = null;

	private HeartBeatThread beatThread = new HeartBeatThread();

	private TraderUtil() {
		mdApi = JCTPMdApi.createFtdcTraderApi(ServerParams.DIRECTORY, false);
		tdApi = JCTPTraderApi.createFtdcTraderApi(ServerParams.DIRECTORY);

		mdSpi = new MyMdSpi(mdApi);
		tdSpi = new MyTraderSpi(tdApi);
	}

	public static TraderUtil instance() {
		return instance;
	}

	public void logon() {
		mdApi.registerSpi(mdSpi);
		tdApi.registerSpi(tdSpi);

		tdApi.subscribePublicTopic(THOST_TE_RESUME_TYPE.THOST_TERT_RESTART);
		tdApi.subscribePrivateTopic(THOST_TE_RESUME_TYPE.THOST_TERT_RESTART);

		mdApi.registerFront(ServerParams.MD_FRONT_ADDR);
		tdApi.registerFront(ServerParams.TD_FRONT_ADDR);

		mdApi.Init();
		tdApi.init();

		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (Exception e) {
		}
		
		beatThread.start();

		mdApi.Join();

		mdApi.Release();
		tdApi.release();
	}

	public void queryTradingAccount() {
		CThostFtdcQryTradingAccountField accountField = new CThostFtdcQryTradingAccountField();
		tdApi.reqQryTradingAccount(accountField, 0);
	}

}
